/*
 * chat_cli.c
 *
 *  Created on: Apr 1, 2012
 *      Author: root
 */


#include	"unp.h"

void str_clie(FILE *fp, int sockfd);
int crlf_add(char *dst, int dstsize, const char *src, int lenin);


int
main(int argc, char **argv)
{
	int					sockfd;
	struct sockaddr_in	servaddr;

	if (argc != 2)
		err_quit("usage: tcpcli <IPaddress>");

	sockfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

	str_clie(stdin, sockfd);		/* do it all */

	exit(0);
}

void
str_clie(FILE *fp, int sockfd)
{
	int			maxfdp1, stdineof;
	fd_set		rset;
	char		buf[MAXLINE];
	char 		buf1[MAXLINE];
	int		n;

	stdineof = 0;
	FD_ZERO(&rset);
	for ( ; ; ) {
		if (stdineof == 0)
			FD_SET(fileno(fp), &rset);
		FD_SET(sockfd, &rset);
		maxfdp1 = max(fileno(fp), sockfd) + 1;
		Select(maxfdp1, &rset, NULL, NULL, NULL);

		memset(buf,0,strlen(buf));

		if (FD_ISSET(sockfd, &rset)) {	/* socket is readable */
			if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
				if (stdineof == 1)
					return;		/* normal termination */
				else
					err_quit("str_cli: server terminated prematurely");
			}
			//if(!strcmp(buf,"asdf\r\n\r\n"))
			//{
			printf("%d\n",strlen(buf));
			Write(fileno(stdout), buf, strlen(buf));
			//printf(" %#x \n",buf);
			//printf("%d\n",strlen(buf));
			memset(buf,0,strlen(buf));
			//}
		}

		if (FD_ISSET(fileno(fp), &rset)) {  /* input is readable */
			if ( (n = Read(fileno(fp), buf, MAXLINE)) == 0) {
				stdineof = 1;
				Shutdown(sockfd, SHUT_WR);	/* send FIN */
				FD_CLR(fileno(fp), &rset);
				continue;
			}
			//char siba='\r';
			//char sss1='\n';
			//printf(" %#x  %#x \n",siba, sss1);

			crlf_add(buf,MAXLINE,buf,n);
			//printf(" %#x \n",buf);
			//Fputs(buf,stdout);////


			 /* input is readable */
		    n = Read(fileno(fp), buf1, MAXLINE);

			crlf_add(buf1,MAXLINE,buf1,n);
			strcat(buf,buf1);

			printf("%d\n",strlen(buf));



			Writen(sockfd, buf, strlen(buf));
			memset(buf,0,strlen(buf));
			memset(buf1,0,strlen(buf));
		}
	}
}


int
crlf_add(char *dst, int dstsize, const char *src, int lenin)
{
	int 	lenout;
	char	c;

	if ( (lenout = lenin) > dstsize)
			err_quit("crlf_add: destination not big enough");

	for ( ; lenin > 0; lenin--) {
		if ( (c = *src++) == '\n') {
			if (++lenout >= dstsize)
				err_quit("crlf_add: destination not big enough");
			*dst++='\r';
		}
		*dst++ = c;

	}

	return(lenout);
}
